package com.xcc.dataStructures.demo14_algapplication;

/**
 * 非递归的二分查找算法
 */
public class Demo01_BinarySearchWithOutRecursion {

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 10, 15};
        System.out.println(search(arr, 8));
    }

    public static int search(int[] arr, int val) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] == val) {
                return mid;
            } else if (arr[mid] > val) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

}
